package pl.edu.agh.mguesser.ui.game;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.PostConstruct;
import javax.swing.JButton;
import javax.swing.JPanel;
import org.springframework.stereotype.Controller;
import pl.edu.agh.mguesser.game.listener.GameStartedListener;
import pl.edu.agh.mguesser.game.listener.StopRequestListener;

/**
 * @author keiran
 */
@Controller
public class StopPlayingPanel extends JPanel implements GameStartedListener,
                                                        StopRequestListener {

    private JButton stopBtn;
    
    private Lock lock = new ReentrantLock();
    private Condition waitingForStop = lock.newCondition();
    
    @PostConstruct
    public void postConstruct() {
        setLayout(new BorderLayout());
        
        stopBtn = new JButton("Stop");
        stopBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                lock.lock();
                try {
                    waitingForStop.signal();

                } finally {
                    lock.unlock();

                }
            }
        });
        
        add(stopBtn, BorderLayout.CENTER);
    }

    @Override
    public void gameStarted() {
        stopBtn.setVisible(false);
    }

    @Override
    public void waitingForStop() {        
        lock.lock();
        stopBtn.setVisible(true);
        
        try {
            waitingForStop.await();
            
        } catch(InterruptedException ex) {
            // just ignore...
            
        } finally {
            stopBtn.setVisible(false);
            lock.unlock();
            
        }
    }

}
